package com.eascs.admin.o2o.notify.service;

import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSON;
import com.eascs.admin.o2o.loan.notify.common.O2OWFService;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.rabbitmq.common.CommonConst;
import com.eascs.rabbitmq.service.ConsumerService;
import com.eascs.workflow.common.vo.ModelResult;
import com.eascs.workflow.common.vo.WFNotifyParam;
import com.eascs.admin.o2o.notify.dao.WFStatusDao;
import com.eascs.admin.o2o.notify.entity.RabbitMsgRecord;

/**
 * 工作流通知接口
 */
@Service("WFMsgNotifyServiceImpl")
public class WFMsgNotifyServiceImpl implements ConsumerService {
	private static Logger log = LoggerFactory.getLogger(WFMsgNotifyServiceImpl.class);

	@Autowired
	private O2OWFService o2oWFService;
	@Autowired
	private WFStatusDao wfStatusDao;

	@Override
	public Boolean exec(String msg) {
		
		log.info("接受来自工作流WFMsgNotifyServiceImpl通知:{}" , msg);
		ModelResult<Boolean> modelResult = new ModelResult<Boolean>();
		try {
			WFNotifyParam notifyParam = JSON.parseObject(msg, WFNotifyParam.class);
			//消息唯一识别码
			//(流程启动会自动通知第一个节点为审核中，导致同一个节点会调用多次消息，因此唯一识别码要加节点状态)
			String uniqueCode = notifyParam.getReferId() + "_" + notifyParam.getProcessId() + "_" + notifyParam.getTaskNode().getTaskNodeId() + "_" + notifyParam.getTaskNode().getNodeStatus();
			//消息重复验证
			RabbitMsgRecord rabbitMsgRecord = wfStatusDao.queryRabbitMsgRecordByUniqueCode(uniqueCode);
			if(rabbitMsgRecord != null){
				log.info("消息重复uniqueCode[{}]", uniqueCode);
				return Boolean.TRUE;
			}
			//消息入库
			rabbitMsgRecord = new RabbitMsgRecord();
			rabbitMsgRecord.setUniqueCode(uniqueCode);
			rabbitMsgRecord.setReferId(notifyParam.getReferId());
			rabbitMsgRecord.setStatus(0);
			rabbitMsgRecord.setMsgType(notifyParam.getProcessType());
			rabbitMsgRecord.setContent(msg);
			rabbitMsgRecord.setCreateTime(new Date());
			wfStatusDao.insertRabbitMsgRecord(rabbitMsgRecord);
			log.info("消息入库成功，uniqueCode[{}]", uniqueCode);
			modelResult = o2oWFService.wfNotify(notifyParam);
			if(modelResult.isSuccess()){
				wfStatusDao.rabbitMsgSucc(uniqueCode);
				log.info("消息消费成功，uniqueCode[{}]", uniqueCode);
			}
			return modelResult.isSuccess();
		} catch (Exception e) {
			log.info("处理工作流通知失败", e);
			modelResult.withError("", "").withStackTrace(e);
			return Boolean.FALSE;
		}
	}

	@Override
	public String getServiceName() {
		return CommonConst.notify_msg_type;
	}

}
